package com.example.skyline.controller;


import com.example.skyline.annotation.LogAnnotation;
import com.example.skyline.common.Result;
import com.example.skyline.service.VideoStreamService;
import com.example.skyline.service.impl.VideoStreamServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController  // 声明为REST控制器
@RequestMapping("/video")  // 基础路径
public class VideoStreamController {
    @Autowired  // 自动注入视频流服务
    private VideoStreamServiceImpl videoStreamService;

    /**
     * 获取FLV流播放地址
     * @param videoId 视频ID
     * @return 包含FLV流地址和状态的响应
     */
    @GetMapping("/play/{videoId}")
    public Object getPlayUrl(@PathVariable Long videoId) {
        // 从数据库获取RTSP地址（伪代码）

        String rtspUrl = "rtsp://stream.strba.sk:1935/strba/VYHLAD_JAZERO.stream";

        try {
            // 转码RTSP为FLV并获取访问路径
            String flvUrl = videoStreamService.convertRtspToFlv(videoId, rtspUrl);

            // 构造响应数据
            Map<String, String> response = new HashMap<>();
            response.put("url", flvUrl);       // FLV流路径
            response.put("status", "online");  // 状态标记
            return ResponseEntity.ok(response);  // 200 OK
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();  // 500错误
        }
    }

    /**
     * FLV流端点，提供持续的FLV视频流
     * @param videoId 视频ID
     * @param response HttpServletResponse对象
     * @return 流式响应
     */
    @GetMapping(value = "/stream/{videoId}", produces = "video/x-flv")
    public ResponseEntity<byte[]> getFlvStream(
            @PathVariable Long videoId,
            HttpServletResponse response) {

        // 设置响应头
        response.setHeader("Content-Type", "video/x-flv");  // FLV内容类型
        response.setHeader("Connection", "keep-alive");     // 保持连接
        response.setHeader("Cache-Control", "no-cache");    // 禁用缓存

        // 实现HTTP流式输出
        try {
            while (true) {
                // 获取最新的FLV数据
                byte[] data = videoStreamService.getFlvData(videoId);
                if (data.length > 0) {
                    // 写入响应流
                    response.getOutputStream().write(data);
                    response.getOutputStream().flush();
                }
                Thread.sleep(100);  // 控制输出频率，避免CPU过高
            }
        } catch (Exception e) {
            // 客户端断开连接时结束
            return ResponseEntity.status(HttpStatus.OK).build();
        }
    }

    /**
     * 停止指定视频的流传输
     * @param videoId 视频ID
     * @return 空响应
     */
    @PostMapping("/stop/{videoId}")
    public ResponseEntity<Void> stopStream(@PathVariable Long videoId) {
        videoStreamService.stopFlvStream(videoId);  // 停止转码
        return ResponseEntity.ok().build();        // 200 OK
    }




}